package com.hz.tgb.filter.logtraceid;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author hezhao created on 2019/12/7 14:56
 */
public class FilterUtils {

    private static final String[] LOG_BODY_MEDIA_TYPE = {"application/json", "application/json;charset=UTF-8",
            "application/x-www-form-urlencoded", "application/xml", "text/plain", "text/xml"};
    private static final String METHOD_GET = "GET";
    private static final String METHOD_OPTIONS = "OPTIONS";

    /**
     * 如果是get请求 或 (不为options请求 且 消息头不是和文件或二进制有关的, 就记录消息体.)
     *
     * @param request
     * @return
     */
    public static boolean requestFilter(HttpServletRequest request) {
        if (METHOD_GET.equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        if (METHOD_OPTIONS.equalsIgnoreCase(request.getMethod())) {
            return false;
        }
        return contentTypeFilter(request.getContentType());
    }

    /**
     * 如果消息头不是和文件或二进制有关的, 就记录消息体.
     *
     * @param response
     * @return
     */
    public static boolean responseFilter(HttpServletResponse response) {
        return contentTypeFilter(response.getContentType());
    }

    private static boolean contentTypeFilter(String contentType) {
        if (StringUtils.isEmpty(contentType)) {
            return true;
        }
        if(Arrays.stream(LOG_BODY_MEDIA_TYPE).anyMatch(e -> e.equalsIgnoreCase(contentType))) {
            return true;
        }
        return false;
    }

    public static boolean filterOptions(HttpServletRequest request) {
        if (METHOD_OPTIONS.equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        return false;
    }

}
